package com.irdstudio.efp.cus.api.rest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.irdstudio.efp.batch.service.facade.OverdueDownService;
import com.irdstudio.basic.framework.core.constant.ResponseData;
import com.irdstudio.basic.framework.core.util.Base64;
import com.irdstudio.basic.framework.core.util.DateUtility;
import com.irdstudio.basic.framework.core.util.FileUtil;
import com.irdstudio.basic.framework.core.util.ZipUtil;
import com.irdstudio.basic.framework.web.controller.AbstractController;

@RestController
@RequestMapping("/api")
public class OverdueDownController extends AbstractController {

	@Value("${localPath}")
	private String locaFilePath;// 本地路径

	@Value("${file.ZXdownloadPath}")
	private String ZXdownloadPath;// 尊享贷下载地址

	@Value("${file.MYdownloadPath}")
	private String MYdownloadPath;// 满意带下载地址

	private static String CTRL_SUFFIX = ".pdf";// 文件后缀
	
	@Autowired
	@Qualifier("overdueDownService")
	private OverdueDownService overdueDownService;

	@GetMapping(value = "/cus/queue/Overdue2/{date}")
	public @ResponseBody ResponseData<Integer> OverdueDownContAll(@PathVariable("date") String date) {

		int code = 0;
		int count = 0;
		String createTime = DateUtility.format8To10(date);
		String times1 = DateUtility.format10To8(date);// 将10位日期转化成8位
		Calendar cal = Calendar.getInstance();
		try {
			// 尊享贷
			String ZXdownload = ZXdownloadPath + times1;
			logger.info("尊享贷下载文件路径：" + ZXdownload);
			File ZXfile = new File(ZXdownload);
			if (ZXfile.exists()) {
				logger.info("尊享贷下载文件开始！");
				down(code, count, createTime, cal, ZXfile, ZXdownload, times1);

			} else {
				logger.info("尊享贷当天文件夹不存在！");
				code = -2;
			}
			// 满意贷
			String MYdownload = MYdownloadPath + times1;
			logger.info("满意贷下载文件路径：" + MYdownload);

			File MYfile = new File(MYdownload);
			if (MYfile.exists()) {
				logger.info("满意贷下载文件开始！");
				down(code, count, createTime, cal, MYfile, MYdownload, times1);
			} else {
				logger.info("满意贷当天文件夹不存在！");
				code = -2;
			}
		} catch (FileNotFoundException e) {
			code = -1;
			logger.error("服务器下载文件出现异常：" + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			code = -1;
			logger.error("服务器下载文件出现异常：" + e.getMessage());
			e.printStackTrace();
		}
		return getResponseData(code);

	}

	private int down(int code, int count, String createTime, Calendar cal, File ZXfile, String zXdownload, String times1)
			throws FileNotFoundException, IOException {
		String locafile = null;

		File[] nfile = ZXfile.listFiles();
		for (File f : nfile) { // 遍历文件夹内所有文件
			if (f.getName().endsWith(CTRL_SUFFIX)) { // 判断文件后缀是否为.pdf
				// 查询文件最新更新日期
				long time = f.lastModified();
				SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd");
				cal.setTimeInMillis(time);
				String times = sdfTime.format(cal.getTime());
				if (createTime.equals(times)) { // 判断是否属于当天文件

					File downfile = f;
					logger.info("文件下载地址为:" + downfile);
					if (zXdownload.equals(ZXdownloadPath + times1)) {
						locafile = locaFilePath + "/" + "尊享贷" + f.getName();
						logger.info("尊享贷文件保存地址为:" + locafile);

					} else if (zXdownload.equals(MYdownloadPath + times1)) {
						locafile = locaFilePath + "/" + "满意贷" + f.getName();
						logger.info("满意贷文件保存地址为:" + locafile);
					}

					FileInputStream fli = new FileInputStream(downfile);
					FileOutputStream fors = new FileOutputStream(locafile);

					byte datas[] = new byte[1024 * 8];
					int len = 0;

					while ((len = fli.read(datas)) != -1) {
						fors.write(datas, 0, len);
					}
					fli.close();
					fors.close();
					count++;

				}
				if (count > 0) {
					code = 0;
					logger.info("文件下载成功！");
				} else {
					code = -2;
					logger.info("当天无pdf文件！");
				}

			}
		}
		return code;
	}

	@GetMapping(value = "/cus/queue/Overdue/{date}")
	public @ResponseBody void getAttachmentById(@PathVariable("date") String date, HttpServletResponse response) {

		SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'z", Locale.ENGLISH);
		try {
			Date date1 = sdf.parse(date);
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
			date = sdf1.format(date1);
		} catch (ParseException e1) {
			logger.error("日期转换出错：" + e1.getMessage());
			e1.printStackTrace();
		}

		String createTime = DateUtility.format10To8(date);
		String fileName = createTime.replace("-", "") + ZipUtil.EXT;// 下载文件名
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			String code = "";
			File file = new File(locaFilePath);
			if (!file.exists()) {
				logger.info("本地文件夹不存在，开始创建文件夹!");
				file.mkdir();
			}
			resultMap = overdueDownService.downloadFile(date,locaFilePath, ZXdownloadPath, MYdownloadPath);
			for (Map.Entry<String, String> entry : resultMap.entrySet()) {
				if("code".equals(entry.getKey())) {
					code = entry.getValue();
					continue;
				}
				strBytesToFileToFile(entry.getValue(), locaFilePath, entry.getKey()+CTRL_SUFFIX);
			}
			ZipUtil.zip(locaFilePath);



		} catch (Exception e) {
			resultMap.put("code", "-1");
		}
		File file = new File(locaFilePath);
		File[] files = file.listFiles();
		for (File downFile : files) { // 遍历文件夹内所有文件

			if (downFile.getName().endsWith(ZipUtil.EXT)) { // 判断文件后缀是否为.zip

				try {
					OutputStream out = response.getOutputStream();
					response.setContentType("application/x-download");
					response.setContentLength((int) downFile.length());
					response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
					BufferedInputStream buff = new BufferedInputStream(new FileInputStream(downFile));
					byte[] b = new byte[1024];
					long k = 0;
					// 开始循环下载
					while (k < downFile.length()) {
						int j = buff.read(b, 0, 1024);
						k += j;
						// 将写入到客户端的内存的数据,刷新到磁盘
						out.write(b, 0, j);
						out.flush();
					}
					buff.close();
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
				downFile.delete();

		}

	}
	
	/**
	 * 
	 * 1、把二进制文件字符串转为文件<br>
	 * 
	 * @param fileBinStr
	 * @param fileName
	 * @return
	 * @since 2019年2月1日 下午6:36:14
	 * @author:ludayong
	 */
	private boolean strBytesToFileToFile(String fileBytStr, String filePath, String fileName) {
		boolean result = false;
		try {
			byte[] newBytes = Base64.decode(fileBytStr);
			FileUtil.writeBytesToFile(newBytes, filePath, fileName);
			result = true;
		} catch (IOException e) {
			logger.error("字节数组转文件出现异常，异常信息" + e.getMessage());
		}
		return result;
	}

	/**
	 * 
	 * 查询是否存在当天文件夹
	 * 
	 * @param date
	 * @return
	 * @author hucy
	 * @since 2019年2月13日 下午2:27:12
	 * @version 1.0
	 */
	@GetMapping(value = "/cus/queue/Query/{date}")
	public @ResponseBody ResponseData<Integer> QueryOverdueDownContAll(@PathVariable("date") String date) {
		int code = 0;

		SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'z", Locale.ENGLISH);
		try {
			Date date1 = sdf.parse(date);
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
			date = sdf1.format(date1);
			try {
				code = overdueDownService.QueryOverdueDown(date, MYdownloadPath, ZXdownloadPath);

			} catch (Exception e) {
				logger.error("查询当天文件出错：" + e.getMessage());
				code = -1;
				e.printStackTrace();
			}
		} catch (ParseException e1) {
			logger.error("日期转换出错：" + e1.getMessage());
			code = -1;
			e1.printStackTrace();
		}
		return getResponseData(code);

	}

}
